package com.msb.mall.product.exception;



import com.msb.common.exception.BizCodeEnume;
import com.msb.common.utils.R;
import com.sun.media.jfxmedia.logging.Logger;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/*
 *
 * 统一的异常处理类
 * */


//@ResponseBody
//@ControllerAdvice
@RestControllerAdvice //组合注解
@Slf4j
public class ExceptionControllerAdvice {

    /*
    处理验证异常的方法
     */

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handlerValidException(MethodArgumentNotValidException e){


//        System.out.println(e.getMessage());
        Map <String,String> map =new HashMap<>();
        e.getFieldErrors().forEach((fieldError)->{
            map.put(fieldError.getField(),fieldError.getDefaultMessage());
        });
        return R.error(BizCodeEnume.VALID_EXCEPTION.getCode(), BizCodeEnume.VALID_EXCEPTION.getMsg()).put("data",map);
    }

    /**
     * 系统异常处理类
     * @param throwable
     * @return
     */

    @ExceptionHandler({Throwable.class})
    public R handlerException(Throwable throwable){

        log.info("错误信息",throwable);
//        return R.error(400,"提交的数据不合法").put("data",throwable.getMessage());
        return R.error(BizCodeEnume.UNKNOW_EXCEPTION.getCode(), BizCodeEnume.UNKNOW_EXCEPTION.getMsg())
                .put("data",throwable.getMessage());
    }

}
